package com.caigou.modules.forum.ui.forum

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.ForumItemAdapter
import com.caigou.modules.forum.bean.PostBean
import com.caigou.modules.forum.databinding.ActivityForumHistoryPostBinding
import com.caigou.modules.forum.viewmodel.ForumViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/21
 */
@Route(path = RouterPath.Forum.PAGE_FORUM_HISTORY_POST)
@AndroidEntryPoint
class ForumHistoryPostActivity : BaseActivity() {

    private lateinit var binding: ActivityForumHistoryPostBinding
    private val forumViewModel: ForumViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.FORUM_TYPE)
    var forumType: Int = 0

    @Autowired(name = AppConstants.USER_ID)
    lateinit var userId: String

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    private val mAdapter: ForumItemAdapter by lazy {
        ForumItemAdapter(mutableListOf())
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityForumHistoryPostBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.historyPostLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.historyPostSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                page = 1
                fetchHistoryPost()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchHistoryPost()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.historyPostRecyclerView.run {
            layoutManager = LinearLayoutManager(this@ForumHistoryPostActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumHistoryPostActivity))
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val postId = mAdapter.getItem(position).id
            ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_POST)
                .withInt(AppConstants.POST_ID, postId)
                .navigation()
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]
            when (view.id) {
                R.id.item_forum_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.userId)
                        .navigation()
                }
            }
        }
        binding.historyPostTvBack.setOnClickListener {
            finish()
        }
        fetchHistoryPost()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(forumViewModel.historyPostListLiveData, ::handleGetHistoryPostList)
    }

    private fun handleGetHistoryPostList(result: Resource<PostBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.historyPostSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取历史信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.historyPostSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    binding.historyPostLlEmpty.visibility = View.GONE
                    binding.historyPostRecyclerView.visibility = View.VISIBLE
                    return
                }
                if (result.data!!.list.isNullOrEmpty()) {
                    binding.historyPostLlEmpty.visibility = View.VISIBLE
                    binding.historyPostRecyclerView.visibility = View.GONE
                } else {
                    binding.historyPostLlEmpty.visibility = View.GONE
                    binding.historyPostRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun fetchHistoryPost() {
        forumViewModel.getForumHistoryList(page, limit, forumType, userId)
    }
}